import { resTol } from '@/tools/public'
import { formatter } from '@/utils/public'

export default {
  methods: {
    initResCodeType(formItems) {
      const selectFitems = formItems.filter(
        e => e.dataType === 'select' && !e.dataRes
      )
      let codeTypeList = []
      for (const item of selectFitems) {
        if (item.dataResCodeType) {
          codeTypeList.push({
            codeType: item.dataResCodeType,
            dataItem: item
          })
        }
      }
      if (codeTypeList.length) {
        return new Promise(resolve => {
          resTol.initReqCodeListResCb(
            codeTypeList.map(e => e.codeType),
            res => {
              for (const code of res) {
                for (const item of codeTypeList) {
                  if (code.codeType === item.codeType) {
                    item.dataItem.dataRes = code.codeList
                  }
                }
              }
              resolve(formItems)
            }
          )
        })
      }
      return Promise.resolve(formItems)
    },
    collectCodeTypeColumns(columns) {
      return columns.filter(c => !!c.dataResCodeType).map(c => c.dataIndex)
    },
    formatCodeTypeColumn(columns, dataIndex, record) {
      return this._formatColumn(
        columns,
        dataIndex,
        record,
        cmn => cmn.dataResCodeType
      )
    },
    collectSelectColumns(columns) {
      return columns.filter(c => c.dataType === 'select').map(c => c.dataIndex)
    },
    formatSelectColumn(columns, dataIndex, record) {
      return this._formatColumn(
        columns,
        dataIndex,
        record,
        cmn => cmn.dataType === 'select'
      )
    },
    _formatColumn(columns, dataIndex, record, canFormatCb) {
      const item = columns.find(c => c.dataIndex === dataIndex)
      if (item && canFormatCb(item) && item.dataRes) {
        let codeName = ''
        if (record[dataIndex] && typeof record[dataIndex] === 'string') {
          for (let code of record[dataIndex].split(',')) {
            if (codeName) {
              codeName += '，'
            }
            codeName += formatter.formatRes(
              item.dataRes,
              code,
              item.dataResItem && item.dataResItem.key,
              item.dataResItem && item.dataResItem.title
            )
          }
        } else {
          codeName = formatter.formatRes(
            item.dataRes,
            record[dataIndex],
            item.dataResItem && item.dataResItem.key,
            item.dataResItem && item.dataResItem.title
          )
        }
        return codeName
      }
      return record[dataIndex]
    }
  }
}
